<?php
class Vistec_Lightspeed_Model_Observer
{
	
protected function _getLsConnectorInstance()
    {        
        $dbAdapterClassName = (string) Mage::getConfig()->getNode()->global->resource->connection->types->{"pdo_mysql"}->class;
    	if ($dbAdapterClassName)
        {
            return new $dbAdapterClassName();
        }
        
        return null;
    }
	
protected function _getLsConnectionDetails()
    {
    	return array(
            'dbname'        => Mage::getStoreConfig('lightspeed/backend/lightspeed_database_name'),
            'username'      => Mage::getStoreConfig('lightspeed/backend/lightspeed_username'),
            'password'      => Mage::getStoreConfig('lightspeed/backend/lightspeed_password'),
            'host'          => Mage::getStoreConfig('lightspeed/backend/lightspeed_server_address'),
            'port'          => Mage::getStoreConfig('lightspeed/backend/lightspeed_port'),
        );
    }
    
    protected function _lsQuery($sql)
    {
    	$vistec_connect = $this->_getLsConnectorInstance();
        $connectionProperties = $this->_getLsConnectionDetails();
        return $vistec_connect->getConnection($connectionProperties)->fetchAll($sql);
    } 
    
    protected function _rawQuery($sql)	{
    	
    	$vistec_connect = $this->_getLsConnectorInstance();
        $connectionProperties = $this->_getLsConnectionDetails();
        return $vistec_connect->getConnection($connectionProperties)->raw_query($sql);
    	
    }
    
	protected function _lastInsertId()	{
    	
    	$vistec_connect = $this->_getLsConnectorInstance();
        $connectionProperties = $this->_getLsConnectionDetails();
        return $vistec_connect->getConnection($connectionProperties)->lastInsertId();
    	
    }
    
    
	
	public function checkComparelog($observer)
	{
		if(!Mage::getStoreConfig('lightspeed/orders/send_orders'))
		{
			return true;
		}
		
		$includeTax=Mage::getStoreConfig('lightspeed/orders/include_tax_remotely');
		$remoteTaxField=Mage::getStoreConfig('lightspeed/orders/remote_tax_field');
		$customerHandling=Mage::getStoreConfig('lightspeed/orders/remote_customer_handling');
		$lsDefaultCurrency=Mage::getStoreConfig('lightspeed/orders/remote_currency_handling');
			
			
		$checkout = $observer->getData('type_onepage');
		$_order = new Mage_Sales_Model_Order();
		$incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
		$_order->loadByIncrementId($incrementId);
		//create an order
		$_order->getShippingAddress()->getFirstname(); 
		$_order->getShippingAddress()->getLastname(); 
		$_order->getShippingAddress()->getCompany(); 
		$_order->getShippingAddress()->getStreet(); 
		$_order->getShippingAddress()->getRegion(); 
		$_order->getShippingAddress()->getCity(); 
		$_order->getShippingAddress()->getPostcode(); 
		$_order->getShippingAddress()->getCountry_id(); 
		
		//process the items
		$items=array();
		$i=0;
		foreach($_order->getAllItems() as $item)
		{
			$arr=array();
			$array['sku']=$item->getData('sku');
			
			$array['row_total']=$item->getData('row_total');
			if($includeTax) {
				$array['row_total']+=$item->getData('tax_amount');
			}	
			$array['qty']=$item->getData('qty_ordered');
			$array['price']=$item->getData('price')/$array['qty'];
			if($includeTax)	{
				$array['price']+=($item->getData('tax_amount')/$array['qty']);
			}
			//TODO get all the other info too
			$items[]=$array;
		}
		//Mage::log("New Order {$items} is the billing address");
		//$sql = "SELECT * FROM xlsws_product as Product";
		//$read = Mage::getSingleton('core/resource')->getConnection('lsremote_read')->fetchAll($sql);
		
		$sql="SELECT SUBSTRING(`id_str` FROM 4) as 'id_str' FROM  xlsws_cart WHERE id_str LIKE 'WO-%'";
		$results = $this->_lsQuery($sql);
		if(count($results)>0)	{
		rsort($results);
		$orderId=$results[0]['id_str']+1;
		$id_str="WO-".$orderId;
		} else {
		$id_str="WO-12000";
		}
		//create an order in lightspeed
		//create an order in lightspeed
		$arrFields=array();
		$arrFields["id_str"]=$id_str;
		$arrFields["address_bill"] = $_order->getBillingAddress()->getName(); 
		$arrFields["address_ship"] = implode(", ",$_order->getShippingAddress()->getStreet());
		$arrFields["ship_firstname"] = $_order->getShippingAddress()->getFirstname(); 
		$arrFields["ship_lastname"] = $_order->getShippingAddress()->getLastname(); 
		$arrFields["ship_company"] = $_order->getShippingAddress()->getCompany();
		$arrFields["ship_address1"] = implode(", ",$_order->getShippingAddress()->getStreet());
		$arrFields["ship_address2"] = $_order->getShippingAddress()->getRegion(); 
		$arrFields["ship_city"] = $_order->getShippingAddress()->getCity(); 
		$arrFields["ship_zip"] = $_order->getShippingAddress()->getPostcode();
		$arrFields["zipcode"] = $_order->getBillingAddress()->getPostcode(); 
		$arrFields["ship_country"] = $_order->getShippingAddress()->getCountry_id(); 
		$arrFields["contact"] = $_order->getBillingAddress()->getName(); 
		//$arrFields["discount"];
		$arrFields["firstname"] = $_order->getBillingAddress()->getFirstname(); 
		$arrFields["lastname"] = $_order->getBillingAddress()->getLastname(); 
		$arrFields["company"] = $_order->getBillingAddress()->getCompany();
		$arrFields["name"] = $_order->getBillingAddress()->getName(); 
		$arrFields["phone"] = $_order->getBillingAddress()->getTelephone();
		$arrFields["ship_phone"] = $_order->getShippingAddress()->getTelephone(); 
		//$arrFields["po"]; //blank
		$arrFields["type"] = 4; //Don't know what this is....
		$arrFields["status"] = "Awaiting Processing";
		//$arrFields["cost_total"]; //blank
		$arrFields["currency"] = $lsDefaultCurrency;
		//$string.=" , currency_rate"];//blank
		$arrFields["datetime_cre"] = date('Y-m-d H:i:s', time());
		$arrFields["datetime_due"] = date('Y-m-d H:i:s', time());
		//$arrFields["datetime_posted"]; $_order->
		$arrFields["email"] = $_order->getCustomerEmail();
		//$arrFields["sell_total"];//blank
		//$arrFields["printed_notes"];//blank
		$arrFields["shipping_method"] = "SHIPPING";
		$arrFields["shipping_module"] = "store_pickup.php"; // flat_rate.php for flat rate delivery or store_pickup.php for pickup
		$arrFields["shipping_data"] = "Store Pickup"; //"Home Delivery Service or Store Pickup from our store"
		
		$arrFields["shipping_cost"] = $_order->getShippingAmount();
		if($includeTax)	{
			$arrFields["shipping_cost"] +=$_order->getShippingTaxAmount();
		}
		//Magento doesn't give a cost price for shipping
		$arrFields["shipping_sell"] = $_order->getShippingAmount();
		if($includeTax)	{
			$arrFields["shipping_sell"] += $_order->getShippingTaxAmount();
		}
		
		$arrFields["payment_method"] = "Cash"; //Cash or Credit Card
		$arrFields["payment_module"] = "phone_order.php";//phone_order.php, paypal.php
		$arrFields["payment_data"] = "Phone Order";//"Phone Order for Pickup, Tel, etc, or UT# from paypal google etc for credit card"
		$arrFields["payment_amount"]= $_order->getTotalPaid();//0 for pickup tel etc, amount for credit card, google, paypal etc.
		$arrFields["fk_tax_code_id"] = 0; //0
		$arrFields["tax_inclusive"] = $includeTax; //1
		$arrFields["subtotal"] = $_order->getBaseSubtotal(); 
		if($includeTax)	{
			$arrFields["subtotal"] = $arrFields["subtotal"]+$_order->getTaxAmount()-$_order->getShippingTaxAmount(); //tax inclusive total
		}
		$arrFields["tax1"]=0;//0
		$arrFields["tax2"]=0;
		$arrFields["tax3"]=0;//0
		$arrFields["tax4"]=0;//0
		$arrFields["tax5"]=0;//0
		$arrFields[$remoteTaxField]=$_order->getTaxAmount();//VAT amount to 12 Decimal places 
		
		$arrFields["total"]=$_order->getGrandTotal();//total shipping, and subtotal
		$arrFields["count"]=count($items);//no of items
		$arrFields["downloaded"]=0;//0
		//$arrFields["user"];//null
		$arrFields["ip_host"]=$_order->getRemoteIP();//host or ip address of customer
		//$arrFields["customer_id"];//leave for now
		//$arrFields["gift_registry"];//null
		//$arrFields["send_to"];
		$arrFields["submitted"]=date('Y-m-d H:i:s', time());
		$arrFields["modified"]=date('Y-m-d H:i:s', time());
		//$arrFields["linkid"]=""; //UUID
		
		$arrFieldNames=(array_keys($arrFields));
		$strFields = "(".implode(", ",$arrFieldNames).",linkid)";
		$strValues = "('".implode("', '",$arrFields)."',UUID())";
		$strInsertQuery="INSERT INTO xlsws_cart ".$strFields." VALUES ".$strValues;
		$insert = $this->_rawQuery($strInsertQuery);
		$cartId = $this->_lastInsertId();
		
		//Customer Handling?
		//If customer handling = new insert new customer, get id, update the cart's customer_id column with the newly created customer id
		if($customerHandling=="new")
		{
		$customerArray=array();
		$customerArray['address1_1']=$_order->getBillingAddress()->getName();
		$customerArray['address1_2']=implode(', ',$_order->getBillingAddress()->getStreet());
		$customerArray['address2_1']=$_order->getShippingAddress()->getName();
		$customerArray['address_2_2']=implode(', ',$_order->getShippingAddress()->getStreet());
		$customerArray['city1']=$_order->getBillingAddress()->getCity();
		$customerArray['city2']=$_order->getShippingAddress()->getCity();
		$customerArray['state1']=$_order->getBillingAddress()->getRegion();
		$customerArray['state2']=$_order->getShippingAddress()->getRegion();
		$customerArray['company']=$_order->getBillingAddress()->getCompany();
		$customerArray['country1']=$_order->getBillingAddress()->getCountry_id();
		$customerArray['country2']=$_order->getShippingAddress()->getCountry_id();
		$customerArray['currency']=$lsDefaultCurrency;
		$customerArray['email']=$_order->getCustomerEmail();
		$customerArray["firstname"] = $_order->getBillingAddress()->getFirstname(); 
		$customerArray["lastname"] = $_order->getBillingAddress()->getLastname(); 
		$customerArray["mainname"] = $_order->getBillingAddress()->getName();
		$customerArray["mainphone"] = $_order->getBillingAddress()->getTelephone();
		$customerArray["mainphone"]["type"] = "mobile"; //Magento Doesn't use phone types
		$customerArray["zip1"] = $_order->getBillingAddress()->getPostcode(); 
		$customerArray["zip2"] = $_order->getShippingAddress()->getPostcode(); 
		$customerArray["password"]=md5('DFSDFDFSDGVFGDFBGBSFAETGFHDSGSDdddddd');
		$customerArray['allow_login']=0; //disable lightspeed login
		$strCustomer=implode("', '",$customerArray);
		
		$arrFieldNames=(array_keys($customerArray));
		$strFields = "(".implode(", ",$arrFieldNames).")";
		$strValues = "('{$strCustomer}')";
		$strInsertQuery="INSERT INTO xlsws_customer ".$strFields." VALUES ".$strValues;
		$insert = $this->_rawQuery($strInsertQuery);
		$customerId = $this->_lastInsertId();
		
		$strUpdateQuery="UPDATE xlsws_cart SET customer_id = '{$customerId}' WHERE rowid = {$cartId}";
		$update = $this->_rawQuery($strUpdateQuery);
		}
		
		
		foreach($items as $item)	{
			
		
			$sql = "SELECT * FROM xlsws_product as Product WHERE code LIKE '".$item['sku']."'";
			$arrResult = $this->_lsQuery($sql);
			
			if(count($arrResult)>0)
			{
				$product=$arrResult[0];
				$date=date('Y-m-d H:i:s', time());
				//add item to cart
				$strInsertQuery = "INSERT INTO xlsws_cart_item
		   (`cart_id`, `cart_type`, `product_id`, `code`, `description`, `discount`, `qty`, `sell`, `sell_base`, `sell_discount`, `sell_total`, `serial_numbers`, `gift_registry_item`, `datetime_added`, `datetime_mod`)
		VALUES
		   ('{$cartId}', 1, '{$product['rowid']}', '{$product['code']}', '{$product['description_short']}', '', '{$item['qty']}', {$item['price']}, {$item['row_total']}, 0, {$item['row_total']}, NULL, 0, '{$date}', '{$date}')";
		   			
				$insert = $this->_rawQuery($strInsertQuery);
				Mage::log("New Order {$items} is the billing address");
				
			}
			
			
			}
		
		
		}
		return true;
}